package net.didactylos.helpline.action;


import java.util.List;

import org.hibernate.*;
import org.hibernate.exception.ConstraintViolationException;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.*;

public class EditUserAction extends HelplineActionBean
{
    @ValidateNestedProperties({
        @Validate(field="username", required=true, maxlength=50),
        @Validate(field="firstNames", required=true, maxlength=50),
        @Validate(field="lastName", required=true, maxlength=50),
        @Validate(field="emailAddress", required=true, maxlength=50, converter=EmailTypeConverter.class)
    })
	private User newUser;
    
    private boolean generatePassword;
    
    private long userId;
    
    private long roleId;
    
    private List<Role> roles;
    
	public User getNewUser()
	{
		return newUser;
	}

	public void setNewUser(User newUser)
	{
		this.newUser = newUser;
	}
		
	public boolean isGeneratePassword()
	{
		return generatePassword;
	}

	public void setGeneratePassword(boolean generatePassword)
	{
		this.generatePassword = generatePassword;
	}

	public long getUserId()
	{
		return userId;
	}

	public void setUserId(long userId)
	{
		this.userId = userId;
	}
	
	public long getRoleId()
	{
		return roleId;
	}

	public void setRoleId(long roleId)
	{
		this.roleId = roleId;
	}

	@SuppressWarnings("unchecked")
	public List<Role> getAllRoles()
	{
		if (roles == null)
		{
			Session session = getContext().getSession();
			roles = session.createCriteria(Role.class).list();
		}
		return roles;
	}
	
	@After(stages=LifecycleStage.BindingAndValidation)
	public void preLoad()
	{
		if (newUser == null)
		{
			Session session = getContext().getSession();
			newUser = (User) session.get(User.class, userId);
			roleId = newUser.getRole().getId();
		}
	}

	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		return new ForwardResolution("editUser.jspx");
	}

	@Secured(Capabilities.SIGN_IN)
	public Resolution editUser()
	{
		Session session = getContext().getSession();
		
		Role role = (Role) session.get(Role.class, roleId);
		if (role == null)
		{
			ValidationError error = new LocalizableError(
					"validation.expression.valueFailedExpression", "roleId", roleId);
            getContext().getValidationErrors().add("roleId", error);
            return getContext().getSourcePageResolution();
		}
		newUser.setRole(role);

		if (generatePassword)
		{
			String password = newUser.generatePassword(10);
			getContext().getMessages().add(new LocalizableMessage("passwordGeneratedMessage", newUser.getUsername(), password));
		}

		try
		{
			session.update(newUser);
		}
		catch (ConstraintViolationException e)
		{
			ValidationError error = new LocalizableError("userExists");
            getContext().getValidationErrors().add("newUser.username", error);
            return getContext().getSourcePageResolution();
		}
        
		return new RedirectResolution(UsersAction.class);
	}

}
